<template>
  <div>
    <Title :title="title"></Title>
    <div ref="chart" style="height: 210px;"></div>
  </div>
</template>
<script>
import { Bar } from '@antv/g2plot';
import { get } from '@/utils/request';
import moment from 'moment';

export default {
  name: 'Pm25Chart',
  data() {
    return {
      title: '今日PM2.5数据监测',
      barData: [],
      barChart: null,
      updateTime: moment().format('YYYY-MM-DD HH:mm'),
      params: { page: 1, pageSize: 100 }
    };
  },
  methods: {
    async fetchData() {
      try {


        // 模拟数据
        await this.processData();
        this.renderChart();
      } catch (error) {
        console.error('数据加载失败:', error);
      }
    },

    async processData() {
      // 生成示例数据（每小时一个数据点）
      const data = [];
      const now = moment().startOf('day');

      for (let i = 0; i < 12; i++) {
        const time = now.format('HH:mm');
        // 生成随机PM2.5值（0-200之间）
        const value = Math.floor(Math.random() * 100);

        data.push({ time, value, type: 'PM2.5' });

        // 增加1小时
        now.add(1, 'hour');
      }

      this.barData = data;
    },

    renderChart() {
      if (!this.$refs.chart) return;

      this.barChart?.destroy();

      this.barChart = new Bar(this.$refs.chart, {
        data: this.barData,
        xField: 'value',
        yField: 'time',
        color: '#36A2EF',
        barStyle: { fill: 'l(270) 0:#36A2EF 1:#4FD6FF' },
        xAxis: {
          title: {
            text: 'PM2.5值 (μg/m³)',
            style: {
              fill: '#333',
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          label: {
            style: {
              fill: '#666',
              fontSize: 11
            }
          },
          grid: { line: { style: { stroke: '#eee' } } }
        },
        yAxis: {
          title: {
            text: '时间',
            style: {
              fill: '#333',
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          label: {
            style: {
              fill: '#666',
              fontSize: 11
            }
          },
          // 关键修改：设置Y轴间隔为1小时
          tickInterval: 1
        },
        label: {
          position: 'right',
          style: { fill: '#fff', fontSize: 10, fontWeight: 'bold' },
          formatter: (datum) => `${datum.value}`
        },
        tooltip: {
          domStyles: {
            'g2-tooltip': {
              background: 'rgba(0, 0, 0, 0.7)',
              color: '#fff',
              fontSize: '12px'
            }
          },
          formatter: (datum) => ({ name: 'PM2.5', value: `${datum.value} μg/m³` })
        }
      });

      this.barChart.render();
    }
  },
  async mounted() {
    await this.fetchData();
  },
  beforeDestroy() {
    this.barChart?.destroy();
  }
};
</script>
<style lang="less" scoped></style>